// @flow
import React, { Component } from 'react'
import styles from './ModelDetailView.css'
import ModelDetail from 'components/ModelDetail'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import TaskList from './TaskList'
import JobList from './JobList'
import CustomerList from './CustomerList'
import DeviceList from './DeviceList'
import StatisticList from './StatisticList'
import FinalList from './FinalList'
import moment from 'moment'
import { Tabs, notification, Form } from 'antd'
import { connect } from 'react-redux'
const TabPane = Tabs.TabPane

type Props = {
  userId: string,
  match: Object,
  history: Object,
  data: Object
}

type States = {
  algInfo: Object,
  taskDatas: Array<Object>,
  jobDatas: Array<Object>,
  finalDatas: Array<Object>,
  deviceDatas: Array<Object>,
  customerDatas: Array<Object>,
  StatisticDatas: Object
}
class ModelDetailView extends Component {
  props: Props
  state: States
  changeTabs: Function
  getAlgInfo: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      algInfo: {},
      taskDatas: [],
      jobDatas: [],
      finalDatas: [],
      deviceDatas: [],
      customerDatas: [],
      StatisticDatas: {}
    }
    this.changeTabs = this.changeTabs.bind(this)
    this.getAlgInfo = this.getAlgInfo.bind(this)
  }

  componentWillMount () {
    const { match } = this.props
    const { id } = match.params
    this.getTaskList(id)
    this.getAlgInfo()
  }

  getAlgInfo () {
    const { match } = this.props
    const { id } = match.params
    universalFetch(`${__SERVICE_API__}analysis/models/${id}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          notification.error({
            message: '提醒',
            description: json.message
          })
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const data = this.props.history.location.state
        const result = Object.assign({}, json.result, { imgUrl: data.data.imgUrl })
        this.setState({
          algInfo: result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  changeTabs (tab: string) {
    const { match } = this.props
    const { id } = match.params
    switch (tab) {
      case '1':
        this.getTaskList(id)
        break
      case '2':
        this.getJobList(id)
        break
      case '3':
        this.getFinalList(id)
        break
      case '4':
        this.getCustomerList(id)
        break
      case '5':
        this.getDeviceList(id)
        break
      case '6':
        this.getStatisticList(id)
        break
      default:
    }
  }

  getStatisticList (id: string) {
    universalFetch(`${__SERVICE_API__}analysis/models/${id}/statistical`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        this.setState({
          StatisticDatas: {
            '模型id': result.modelId,
            '客户个数': result.customerCount,
            '设备个数': result.deviceCount,
            '作业个数': result.jobCount,
            '任务个数': result.taskCount,
            '总的预警个数': result.warningCount.allCount,
            '站内预警的个数': result.warningCount.amqCount,
            '忽略的个数': result.warningCount.ignoreCount,
            '邮件处理的个数': result.warningCount.mailCount,
            '不做处理的个数': result.warningCount.noDealCount,
            '短信处理的个数': result.warningCount.smsCount,
            '生成工单的个数': result.warningCount.orderCount
          }
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getCustomerList (id: string) {
    universalFetch(`${__SERVICE_API__}analysis/models/${id}/customers`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          customerDatas: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getDeviceList (id: string) {
    universalFetch(`${__SERVICE_API__}analysis/models/${id}/devices`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          deviceDatas: json.result.map((d, i) => {
            d['operationDate'] = moment(d.operationDate).format('YYYY-MM-DD')
            d['produceDate'] = moment(d.produceDate).format('YYYY-MM-DD')
            d['latestRepairDate'] = moment(d.latestRepairDate).format('YYYY-MM-DD HH:mm:ss')
            return d
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getJobList (id: string) {
    universalFetch(`${__SERVICE_API__}analysis/models/${id}/jobs`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          jobDatas: json.result.map((d, i) => {
            d['startTime'] = moment(d.startTime).utc().format('YYYY-MM-DD HH:mm:ss')
            d['endTime'] = d.status === 'FINISHED' ? moment(d.endTime).utc().format('YYYY-MM-DD HH:mm:ss') : ''
            return d
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getFinalList (id: string) {
    universalFetch(`${__SERVICE_API__}analysis/models/${id}/interfaces`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          finalDatas: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getTaskList (id: string) {
    universalFetch(`${__SERVICE_API__}analysis/models/${id}/tasks`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          taskDatas: json.result.map((d, i) => {
            d['startDate'] = moment(d.startDate).format('YYYY-MM-DD HH:mm:ss')
            d['endDate'] = moment(d.endDate).format('YYYY-MM-DD HH:mm:ss')
            return d
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  render () {
    const { algInfo, taskDatas, jobDatas, deviceDatas, customerDatas, finalDatas, StatisticDatas } = this.state
    let finalShow = true
    if (algInfo.tasks) {
      if (algInfo.tasks.length > 0) {
        if (algInfo.tasks[0].result === 'warning') {
          finalShow = false
        }
      }
    }

    const { history } = this.props
    return (
      <div className={styles['main']}>
        <ModelDetail {...{
          algInfo
        }} />
        <div className={styles['content']}>
          <Tabs defaultActiveKey='1' onChange={this.changeTabs} type='card'>
            <TabPane key='1' tab='分析任务'>
              <TaskList {...{
                data: taskDatas
              }} />
            </TabPane>
            <TabPane key='2' tab='分析作业'>
              <JobList {...{
                history,
                data: jobDatas
              }} />
            </TabPane>
            <TabPane key='3' tab='分析结果' disabled={finalShow}>
              <FinalList {...{
                data: finalDatas
              }} />
            </TabPane>
            <TabPane key='4' tab='客户'>
              <CustomerList {...{
                data: customerDatas
              }} />
            </TabPane>
            <TabPane key='5' tab='设备'>
              <DeviceList {...{
                data: deviceDatas
              }} />
            </TabPane>
            <TabPane key='6' tab='统计性指标'>
              <StatisticList {...{
                data: StatisticDatas
              }} />
            </TabPane>
          </Tabs>
        </div>
      </div>
    )
  }
}
const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Form.create()(ModelDetailView))
